﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLBH.ModelInterface;
using QLBH.DataModel;
using QLBH.Model.Controller;
using QLBH.Base;
using QLBH.StandardUI;
using QLBH.ModelFactory;
using System.Transactions;

namespace QLBH.CongNo
{
    public partial class Thu_Tra_NoDlg : Form
    {
        private eThuTraNO type;
        private ISoNoModel model;

        public ISoNoModel Model
        {
            get { return model; }
            set 
            { 
                model = value; 
                
                if (model!=null)
                {
                    if (model.KHID!=Guid.Empty)
                    {
                        KHACHHANG kh=KhachHangController.GetInstance().FindBy(e=>e.KHID==model.KHID).FirstOrDefault();
                        if (kh != null)
                        {
                            //KH
                            tbxHoTen.Text = kh.TENKH;
                            tbxEmail.Text = kh.EMAIL;
                            tbxSDT.Text = kh.DIDONG;
                            rtbxDiaChi.Text = kh.DIACHI;
                        }
                    }
                    else
                    {
                        //NCC
                        NHACUNGCAP ncc = NCCController.GetInstance().FindBy(e => e.NCCUID == model.NCCID).FirstOrDefault();
                        if (ncc != null)
                        {
                            //KH
                            tbxHoTen.Text = ncc.TENNCC;
                            tbxEmail.Text = ncc.EMAIL;
                            tbxSDT.Text = ncc.DIDONG;
                            rtbxDiaChi.Text = ncc.DIACHI;
                        }
                    }
                    decimal noCon = model.SOTIEN - model.DATRA;
                    tbxSoTienNo.Text = noCon.ToString();
                }
            }
        }
        public Thu_Tra_NoDlg(eThuTraNO type)
        {
            InitializeComponent();
            this.type = type;
            
            if (type==eThuTraNO.THUNO)
            {
                groupBox2.Text = "Thu nợ của";
                this.Text = "Thu Nợ";
                label7.Text = "Số tiền thu";
            }
            else
            {
                groupBox2.Text = "Trả nợ cho";
                this.Text = "Trả Nợ";
                label7.Text = "Số tiền trả";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckInputValue())
            {
                //Save data
                model.DATRA += decimal.Parse(tbxTienThu.Text);

                model.NGAYCAPNHAT = DateTime.Now;

                SONO entity = model.ToEntity();
                try
                {
                    // define our transaction scope
                    var scope = new TransactionScope(
                        // a new transaction will always be created
                        TransactionScopeOption.RequiresNew,
                        // we will allow volatile data to be read during transaction
                        new TransactionOptions()
                        {
                            IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
                        }
                    );
                    using (scope)
                    {
                        entity = SoNoController.GetInstance().Edit(entity);

                        //save data to history

                        ILichSuThuNoModel history = CongNoModelFactory.GetLichSuThuNoModelInstance();
                        history.ID = Guid.NewGuid();
                        history.SONOID = entity.SONOID;
                        history.SOTIEN = decimal.Parse(tbxTienThu.Text);
                        history.NGAYTAO = DateTime.Now;
                        history.USERID = AccountHandler.GetCurrentUserLogin().NVID;
                        history.GHICHU = rtbxGhiChu.Text;

                        LICHSUTHUTRANO hisEntity = history.ToEntity();

                        LichSuTraNoController.GetInstance().Add(hisEntity);

                        scope.Complete();
                    }                    
                }
                catch (System.Exception ex)
                {
                    ShowMessage.Instance.ShowError(ex.Message);
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
                
                if (entity.SOTIEN==entity.DATRA)
                {
                    //Da tra het no.
                    String sms;
                    if (type==eThuTraNO.THUNO)
                    {
                        sms=String.Format("'{0}' đã trả hết nợ, bạn có muốn xóa khỏi sổ nợ không?",tbxHoTen.Text);
                    }
                    else
                    {
                        sms = String.Format("Bạn đã trả hết nợ cho '{0}', bạn có muốn xóa khỏi sổ nợ không?", tbxHoTen.Text);
                    }

                    if (ShowMessage.Instance.ShowQuestion(sms) == DialogResult.Yes)
                    {
                        //Xoa khoi so no
                        try
                        {
                            SoNoController.GetInstance().Delete(entity);
                        }
                        catch (System.Exception ex)
                        {
                            ShowMessage.Instance.ShowError(ex.Message);
                            this.DialogResult = DialogResult.Cancel;
                            this.Close();
                        }
                    }                    
                }

                //return and close dialog
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private bool CheckInputValue()
        {
            try
            {
                DataInputHelper.CheckDecimalData(tbxSoTienNo.Text, "Số tiền nợ");
            }
            catch (System.Exception ex)
            {
                ShowMessage.Instance.ShowError(ex.Message);
                tbxSoTienNo.SelectAll();
                tbxSoTienNo.Focus();
                return false;
            }
            try
            {
                DataInputHelper.CheckDecimalData(tbxTienThu.Text, "Tiền trả");
            }
            catch (System.Exception ex)
            {
                ShowMessage.Instance.ShowError(ex.Message);
                tbxTienThu.SelectAll();
                tbxTienThu.Focus();
                return false;
            }

            if (decimal.Parse(tbxTienThu.Text)>decimal.Parse(tbxSoTienNo.Text))
            {
                ShowMessage.Instance.ShowError("Số tiền trả lớn hơn số tiền cần trả");
                tbxTienThu.SelectAll();
                tbxTienThu.Focus();
                return false;
            }
            return true;
        }

        private void Thu_Tra_NoDlg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Escape)
            {
                btnCancel_Click(btnCancel, null);
            }
            else if (e.Control && e.KeyCode==Keys.S)
            {
                btnSave_Click(btnSave, null);
            }
        }
    }
    public enum eThuTraNO
    {
        THUNO,
        TRANO
    };
}
